<template>
	<div class="newLive w944">
		<alert ref="alert"></alert>
			<labelAll ref="labelAll" :LabelsIds="LabelsIds" :LabelsNames="LabelsNames" v-on:labelNamesChanges="reveiceChange($event)"></labelAll>
		<div class="label_top">
			<button @click="cancel"><i><&nbsp;</i>返回</button>
			<p>{{updateTitle}}</p>
		</div>
		<div class="newLive_content">
			<div class="liveLine inputDiv marB"><span>直播名称：</span>
				<el-input placeholder="请输入直播名称" v-model="courseName"></el-input>
			</div>
			<div class="liveLine marB"><span>直播分类：</span>
				<el-select v-model="courseColumnYi" placeholder="请选择一级分类" @change="selectChange(courseColumnYi,KcColumnYi)">
					<el-option v-for="item in KcColumnYi" :key="item.id" :label="item.columnName" :value="item.id">
					</el-option>
				</el-select>
				<el-select v-model="courseColumn" placeholder="请选择子分类">
					<el-option v-for="item in KcColumnEr" :key="item.id" :label="item.columnName" :value="item.id">
					</el-option>
				</el-select>
			</div>
			<div class="liveLine marB arrow"><span>讲师名字：</span>
				<el-select v-model="speakerId" placeholder="请选择或搜索" filterable :filter-method="selectSearch" style="margin-left: 0;" :disabled="this.Fromtype=='lectureType'?true:false">
			        <el-option v-for="item in lectureoption" :key="item.id" :label="item.nickname" :value="item.id"></el-option>
			  </el-select>
			</div>
			<div class="liveLine marB">
				<span>章节学分：</span>
				<el-input placeholder="0-5分" v-model="courseScore" style="ime-mode:disabled;display: inline-block;width: 162px;" onKeyUp="this.value=this.value.replace(/[^\.\d]/g,'');this.value=this.value.replace('.','');" @blur="getScore" id="score"></el-input> 
				<em>每个章节完成后学员获得的学分奖励</em>
			</div>
			<div class="liveLine">
				<div style="overflow: hidden;">
					<span class="tit" style="float: left;">直播标签：</span>
					<div class="labelFour"><span v-for="item in this.LabelsNames">{{item}}</span></div>
					<a @click="openLabel" class="openLabel">选择标签</a>
				</div>
				<p class="labelWarn">最多可选四个标签</p>
			</div>
			<div class="platformLogo">
				<span>列表图片：</span>
				<div class="platformImg">
					<el-upload class="avatar-uploader" refs="uploadxls" action="http://www.h3clearning.com/huathree-back/uploadFile" :headers="myHeaders" :show-file-list="false" :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess">
						<img v-if="courseImg" :src="courseImg" class="avatar">
						<i v-else class="el-icon-plus avatar-uploader-icon"><b style="display:block;font-weight:normal"><em>上传图片</em></b></i>
					</el-upload>
					<em>建议尺寸为320*180像素，大小小于1M</em>
				</div>
			</div>
			<div class="liveLine">
				<span style="margin-bottom: 15px;display: block;" class="tit">直播介绍：</span>
				<vue-ueditor-wrap v-model="courseDesc" :config="myConfig" style="margin-left: 74px;"></vue-ueditor-wrap>
			</div>
			<div class="footerButton">
				<a @click="checkSave" v-bind:style="{background: clickLock==true ? '#44CEF6' : '#3a8ee6'}">保存</a>
				<a @click="cancel" class="cancel">取消</a>
			</div>
		</div>
	</div>
</template>

<script>
	import alert from '../../components/Alert.vue';
	import labelAll from '../../components/label.vue';
	export default{
		data(){
			return{
				LabelsIds:[],
				LabelsNames:[],
				labelType:'newLive',
				nowType: 'add',
				updateTitle:'创建直播课程',
				clickLock:true,
				Fromtype:'',
				id: '',
				checkedCities:[],
				userAttributes:[],
				courseName:'',
				KcColumnYi: [],
				KcColumnEr: [],
				courseColumnYi: '',
				courseColumn: '',
				speakerId:'',
				lectureoption: [],
				lectureoptionCopy: [],
				courseScore:'',
				courseImg:'',
				courseDesc:'',
				myConfig: {
					autoHeightEnabled: false,
					initialFrameHeight: 420,
					initialFrameWidth: '840',
				},
				checkedSelectionIds:[],
				myHeaders:{Authorization:this.$root.userInfoMsg.sessionId}
			}
		},
		methods: {
			getParams() {
				var routerParams = this.$route.params.type;
				if(routerParams == 'edit') {
					this.nowType = 'edit';
					this.updateTitle = "编辑直播课程";
				}else{
					this.nowType = 'add';
				};
				this.Fromtype = this.$route.params.Fromtype;
				if(this.Fromtype == 'lectureType') {
					this.speakerId = this.$route.params.lecturerid;
					this.speakerName = this.$route.params.updateTitle;
				};
				console.log('newLive:',this.$route.params);
			},
			selectSearch(val){
				this.value = val;
		        if (val) { 
		            this.lectureoption = this.lectureoptionCopy.filter((item) => {
		                if (!!~item.nickname.indexOf(val) || !!~item.nickname.toUpperCase().indexOf(val.toUpperCase())) {
		                	return true
		                }
		            })
		        }else {
		          this.lectureoption = this.lectureoptionCopy;
		        }
			},
			getScore(){
				if(this.courseScore>5){
					this.$refs.alert.show({
						alertText: '学分最大值为5！',
						alertSubmit: function() {
							alertStatus: 0
						}
					});
					$('#score').focus();
				}
			},
			openLabel(){
				this.$refs.labelAll.labelTable=true;
			},
			reveiceChange(event){
				this.LabelsIds = event.arg1;
	        	this.LabelsNames = event.arg2;
	     	},
			createLive() {
				//新建课程
				let that = this;
				var arr = this.LabelsIds.concat(this.checkedSelectionIds);
				let s = {
					rootcompanyid:1,
					courseName: that.courseName, 
					courseColumnYi: that.courseColumnYi,
					courseColumn: that.courseColumn,
					speakerId: that.speakerId,
					courseScore: that.courseScore,
					courseImg: that.courseImg,
					courseDesc: that.courseDesc,
					courseLabels:arr.join(',')
				};
				if(this.clickLock==true){
					this.clickLock = false;
					this.$ajax({
						url: this.$root.jifuUrl + '/addLiveBroadcastCourse',
						data: this.qs.stringify(s),				
						method: 'POST',
						success: res => {
							if(res.data.code == 200) {
								this.$refs.alert.show({alertText: '保存成功'});
								setTimeout(() =>{
									this.$router.push({
										name:'liveManager'
									});
								},2000)
							}else{
								this.clickLock = true;
								this.failText = res.data.message;
								this.$rootFunction().deleteResFail();
							}
						}
					});
				}
			},
			updateLive(){
				let that = this;
				var arr = this.LabelsIds.concat(this.checkedSelectionIds);
				let s = {
					id:that.id,
					rootcompanyid:1,
					courseName: that.courseName,
					courseColumnYi: that.courseColumnYi,
					courseColumn: that.courseColumn,
					speakerId: that.speakerId,
					courseScore: that.courseScore,
					courseImg: that.courseImg,
					courseDesc: that.courseDesc,
					courseLabels:arr.join(',')
				};
				this.$ajax({
					url: this.$root.jifuUrl + '/updateLiveBroadcastCourse',
					data: this.qs.stringify(s),				
					method: 'POST',
					success: res => {
						if(res.data.code == 200) {
							this.$refs.alert.show({alertText: '保存成功'});
							setTimeout(() =>{
								this.$router.push({
									name:'liveManager'
								});
							},2000)
						}else{
							this.failText = res.data.message;
							this.$rootFunction().deleteResFail();
						}
					}
				});
			},
			checkSave() {
				let that = this;
				if(that.nowType == 'add') {
					that.createLive();
				}else if(that.nowType == 'edit') {
					that.updateLive();
				}
			},
			cancel() {
				this.$router.go(-1);
			},
			selectChange(courseColumnYi,KcColumnYi) {
				this.courseColumn='';
				this.KcColumnEr = '';
                this.KcColumnYi.forEach(element => {
                    if(element.id==courseColumnYi){
                        this.KcColumnEr = element.childList;
                    }
                });
            },
			handleAvatarSuccess(res, file) {
				if(res.code == 200) {
					this.courseImg = res.data[0];
				};
			},
			beforeAvatarUpload(file) {
				const isJPG = (file.type === 'image/jpeg') || (file.type === 'image/png');
				const isLt2M = file.size / 1024 / 1024 < 2;
				if(!isLt2M) {
					this.$message.error('上传图片大小不能超过 2MB!');
				}
				return isJPG && isLt2M;
			},
			getColumnList(){
				let columnType = [5];
				this.$rootFunction().columnListAdd({columnType});
			}
		},
		components: {
			alert,
			labelAll
		},
		mounted(){
			this.getParams();
			if(this.updateTitle==null){
				this.$store.commit('GET_newLive');
				var s =this.$store.state.newLive;
				this.Fromtype=s.Fromtype;
				this.speakerId=s.speakerId;
				this.speakerName=s.speakerName;
			};
			if(this.nowType == "edit") {
				console.log('306', this.nowType, this.$root.liveMsg);
				this.id = this.$root.liveMsg.id;
				this.courseName = this.$root.liveMsg.courseName;
				this.rootcompanyid = this.$root.liveMsg.rootcompanyid;
				this.speakerId = this.$root.liveMsg.speakerId;
				this.courseColumnYi = this.$root.liveMsg.courseColumnYi;
				this.courseColumn = this.$root.liveMsg.courseColumn;
				this.courseDesc = this.$root.liveMsg.courseDesc;
				this.courseScore = this.$root.liveMsg.courseScore;
				this.courseImg = this.$root.liveMsg.courseImg;
				
				if(this.$root.liveMsg.userRoleId!=null){
					let userIds = this.$root.liveMsg.userRoleId.split(',');
					userIds.forEach(element => {
						this.checkedCities.push(parseInt(element));
						this.checkedSelectionIds.push(parseInt(element));
	                });
				};
				if(this.$root.liveMsg.labelId!=null){
					let aaa = this.$root.liveMsg.labelId.split(',');
					let bbb = this.$root.liveMsg.labelName.split(',');
					aaa.forEach(element => {
						this.LabelsIds.push(element)
					});
					bbb.forEach(element => {
						this.LabelsNames.push(element)
					});
				};
			};
			this.getColumnList();
			this.$rootFunction().getAllLecture();
			window.addEventListener("beforeunload",()=>{
				s={
					Fromtype:this.Fromtype,
					speakerId:this.speakerId,
					speakerName:this.speakerName
				}
				this.$store.commit('SET_newLive', s);
			});
		}
	}
</script>

<style>
	.newLive_content{position: relative;}
	.newLive_content span{font-size: 16px;color: #333;height:32px;line-height:32px;}
	.newLive_content .el-input input {width:148px;height:34px;display:inline-block;font-size:14px;color:#333;position:relative;left:-5px;}
	.newLive_content .inputDiv .el-input,.newLive_content .inputDiv .el-input input{width:300px;}
	.newLive_content em {font-size:14px;color:#ccc;font-style:normal;}
	.newLive_content .teacherSkills {position:relative;height:34px;line-height:34px;}
	.newLive_content .skillDetail {width:450px;height:32px;line-height:32px;border:1px solid #ccc;border-radius:5px;position:absolute;top:0;left:81px;}
	.newLive_content .skillDetail i {font-style:normal;color:#ccc;position:relative;top:-4px;margin-left:4px;cursor:pointer;}
	.newLive_content .skillDetail span,.newLive_content .skillContent span {color:#44CEF6!important;font-size:14px;width:auto!important;margin-left:15px;cursor:pointer;}
	.newLive_content .skillContent {margin-left:86px;height:auto!important;width:607px;line-height:28px}
	.newLive_content .platformLogo{height: 120px!important;position: absolute;top: 0;left: 500px;width: 310px;}
	.newLive_content .platformImg{position: absolute;top: 0;left: 80px;}
	.newLive_content .platformImg .avatar-uploader{width: 100px;height: 100px;}
	.newLive_content .platformImg .avatar-uploader img{width: 100%;}
	.newLive_content .platformImg .avatar-uploader-icon{font-size:28px;color:#8c939d;width:100px;height:75px!important;padding-top:25px;text-align:center;background:#f2f2f2;    border-radius: 5px;}
	.newLive_content .platformImg .el-upload i em{font-size:14px;color:#ccc;font-style:normal;text-align:center;display:block;margin-top:6px;}
	.newLive_content .platformImg em{font-style:normal;font-size:12px;color:#ccc;margin-top:8px;display:block;line-height:16px;}
	.newLive_content .labelFour{width: 400px;height: 33px;line-height: 33px;border: 1px solid #ccc;border-radius: 5px 0 0 5px;display: inline-block;box-sizing: border-box;float: left;}
	.newLive_content .labelFour span{position: relative;top: -2px;font-size: 14px;color: #333;margin-left: 16px;display: inline-block;}
	.newLive_content .openLabel{float: left;}
	.newLive_content .labelWarn{font-size: 12px;color: #999;margin-left: 87px;margin-top:10px}
	.newLive_content .liveLine a{width: 80px;height: 33px;line-height: 33px;display: inline-block;color: #fff;margin-left: -5px;background: #44CEF6;text-align: center;font-size: 14px;border-radius: 0 5px 5px 0;box-sizing: border-box;cursor: pointer;}
	.el-input__suffix span{line-height:46px!important;}
</style>